﻿using System.Collections.ObjectModel;
using System.ComponentModel.Composition;
using System.Windows;
using Silverlight.Training.Client.Common;
using Silverlight.Training.Client.Common.ServiceReference.Contracts;
using Silverlight.Training.Client.Common.ServiceReference.EventArgs;
using SilverLight.Training.Models;

namespace SilverLight.Training.ViewModels
{
    [Export]
    public class EmployeeDetailsViewModel : NotifyPropertyChangedBase
    {
        private EmployeeDetailsModel model;

        [ImportingConstructor]
        public EmployeeDetailsViewModel()
        {
            model = new EmployeeDetailsModel();
            model.GetEmployeeCollectionCompleted += model_GetEmployeeCollectionCompleted;
            model.GetEmployeeCollectionAsync();
            model.GetSingleEmployeeCompleted += model_GetSingleEmployeeCompleted;
            model.GetSingleEmployeeAsync(1);
        }

        void model_GetEmployeeCollectionCompleted(object sender, CollectionFeedbackCompletedEventArgs<Employee> e)
        {
            if (e.Error == null)
            {
                if (e.Result != null)
                    EmployeeCollection = e.Result.Data;
                else
                {
                    MessageBox.Show("No result.");
                }
            }
            else 
            {
                MessageBox.Show("Error: " + e.Error);
            }
        }

        void model_GetSingleEmployeeCompleted(object sender, SingleFeedbackCompletedEventArgs<Employee> e)
        {
            if (e.Error == null)
            {
                if (e.Result != null)
                {
                    MessageBox.Show(e.Result.Message);

                    if (e.Result.IsSuccessful)
                    {
                        Employee = e.Result.Data;
                    }
                }
                else
                {
                    MessageBox.Show("No result.");
                }
            }
            else
            {
                MessageBox.Show("Error: " + e.Error);
            }
        }

        private ObservableCollection<Employee> employeeCollection;
        public ObservableCollection<Employee> EmployeeCollection
        {
            get{return employeeCollection;}
            set
            {
                if (!ReferenceEquals(value, employeeCollection))
                {
                    employeeCollection = value;
                    RaisePropertyChanged("EmployeeCollection");
                }
            }
        }

        private Employee employee;
        public Employee Employee
        {
            get { return employee; }
            set
            {
                if (!ReferenceEquals(employee, value))
                {
                    employee = value;
                    RaisePropertyChanged("Employee");
                }
            }
        }
    }
}
